﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace ICodeShare.UI.Interactivity
{
    public class PasswordBoxBindingBehavior : Behavior<PasswordBox>
    {
        private static bool IsUpdating;


        public static string GetPassword(DependencyObject dpo)
        {
            return (string)dpo.GetValue(PasswordProperty);
        }
        public static void SetPassword(DependencyObject dpo, string value)
        {
            dpo.SetValue(PasswordProperty, value);
        }


        public static readonly DependencyProperty PasswordProperty = DependencyProperty.Register(
            "Password", typeof(string), typeof(PasswordBoxBindingBehavior), new PropertyMetadata(default(string), OnPasswordPropertyChanged));

        private static void OnPasswordPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox targetPasswordBox = dependencyObject
                
                as PasswordBox;
            if (targetPasswordBox != null)
            {
                targetPasswordBox.PasswordChanged -= PasswordBox_PasswordChanged;
                if (IsUpdating == false)
                {
                    targetPasswordBox.Password = (string)e.NewValue;
                }
                targetPasswordBox.PasswordChanged += PasswordBox_PasswordChanged;
            }
        }


        private static void PasswordBox_PasswordChanged(object sender, RoutedEventArgs args)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            IsUpdating = true;
            SetPassword(passwordBox, passwordBox.Password);
            IsUpdating = false;
        }

        #region 重写方法

        #region 注册事件
        /// <summary>
        /// 注册事件
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.PasswordChanged += PasswordBox_PasswordChanged;
        }

        #endregion

        #region 注销事件
        /// <summary>
        /// 注销事件
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.PasswordChanged -= PasswordBox_PasswordChanged;
        }
        #endregion

        #endregion
    }
}
